import { App, Modal, sanitizeHTMLToDom, Setting } from 'obsidian';

export interface ConfirmModalOptions {
	info?: string;
	title?: string;
	elementHTML?: string;
	setName?: string;
	setInfo?: string;
	buttons?: { btnText?: string; btnAction?: () => any; }[];
}
export class ConfirmModal extends Modal {
	#finised: Promise<boolean>;
	constructor(app: App, options: ConfirmModalOptions) {
		super(app);

		const { info = '', title = '', elementHTML = '', setName = '', setInfo = '', buttons = [{ btnText: '', btnAction: undefined }] } = options;
		this.contentEl.createEl("h2", { text: title });
		this.contentEl.createEl("p", { text: info });
		this.contentEl.append(sanitizeHTMLToDom(elementHTML));

		const btnSetting = new Setting(this.contentEl)
			.setName(setName);
		if (setInfo != '') btnSetting.infoEl.setText(setInfo);
		this.#finised = new Promise((resolve) => {
			buttons.forEach((button) => {
				btnSetting.addButton((btn) => {
					btn
						.setButtonText(button.btnText ?? '退出')
						.setCta()
						.onClick(async () => {
							btn.setDisabled(true)
							button.btnAction && await button.btnAction();
							resolve(true);
							this.close();
						});
				});
			});
		})
	}

	get finised() {
		return this.#finised;
	}

}
